const api = require("../../../config/api")
const request = require("../../../utils/request")
const app = getApp()
import lottie from '../../../utils/lottie'
const {
	saveImage
} = require('../../../utils/photo')
const env = __wxConfig.envVersion
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		break:false,// 中断状态
		activityDetail:{},
		activityActive: true, // 活动是否正在进行
		LJInfo:{},
		ossurl: 'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com',
		topImageUrl: '/zhiliao-applet/Q6p91kLL8d5v234d64cb2e970908c2c3fe4a6cfcbf29.png',
		greenBackUrl: '/zhiliao-applet/Qsrwn12A8xp58b5d069cf94926db4d7e5a67ba8987d4.png',
		trainUrl: '/zhiliao-applet/ZqcgnpnKTPcC16dc4da57e482ee232dd02c72038c0d0.png',
		todayTask: '/zhiliao-applet/1hK6zYsTqFaB2585c76f703b2df676356a3898493986.png',
		warningUrl: '/zhiliao-applet/gZPoDGeQP5Y49687cc933a26784d53fc14297f84dabc.png',
		sucessUrl: '/zhiliao-applet/RC6PGzMwU16j10de26b40e51a820ed14426843f55d8b.png',
		moreTrain: '/zhiliao-applet/seFTURXaH99sb14c8ceb71cc94baf873ded2bffc0aec.png',
		posterImg: 'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zhiliao-applet/CmcFNMinKpDV8835b43bb6765ed5d0aaa8d699de15d4.png', // 海报图片
		codeImg: '', // 用户小程序码
		imagePath: '',
		canvasHeight: 0,
		canvasWidth: 0,
		activityId: '',
		showPoster: false,
		modalHeight: app.kBottomSafeHeight + 345,
		showSceneList: [], //训练列表
		todayTaskList: [], //今日任务
		trainingName: '',
		isMeetCondition: 0, //是否满足领奖条件，1 已满足 / 0 未满足
		isFillAddress: 0, //是否已填写收货信息，1 已填写 / 0 未填写
		isLastDayTask: 0, //是否最后一天任务，1 是 / 0 不是
		isAllComplete: 0,
		hasGetStatus:false,
		env: env,
		showSheet: false
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		if(options.activityId){
			this.setData({
				activityId: options.activityId
			})
			wx.setStorageSync("awardActicityId", options.activityId)
		}
		
		this.getTrainListData()

		wx.getSystemInfo({
			success: (result) => {
				console.log('rrr',result);
				let GreenHeight = result.windowHeight-140
				this.setData({
					GreenHeight
				})
			},
		})
	},

	// 获取学习认知、趣味感统类型的场景训练
	getCompleteTrainList:async function(){
		const res = await request.get(api.getCompleteTraining,{},{loading:false})
		if(res.data){
			this.setData({
				showSceneList:[...res.data]
			})
		}
	},

	// 跳转训练详情
	toTrainDetail:function(e){
		let {hasGetStatus,isMeetCondition} = this.data
		if(hasGetStatus&&isMeetCondition===1){
			let trainingId = e.currentTarget?.dataset?.id
			wx.navigateTo({
				url: `/pages/sceneTrainDetail/index?trainingId=${trainingId}`,
			})
		}
	},

	// 去完成任务
	toCompleteTask: function () {
		let {todayTaskList, activityId} = this.data
		let item = todayTaskList.find((item)=>{
			return item.state!==4
		})
		app.globalData.finishTaskEntrance = 5
		if (Number(item.trainingType) === 1) {
      wx.navigateTo({
        url: '/pages/sceneTaskDetail/index?fromOrigin=1&origin=1&id=' + item.detailId+'&activityId='+activityId,
      })
    } else {
      wx.navigateTo({
        url:
          '/pages/selfAssessment/question/index?fromOrigin=1&key=1&id=' +
          item.questionnaireId +
          '&pathId=' +
          item.trainingId +
          '&taskFlowId=' +
          item.detailId+
          '&activityId='+activityId,
      })
    }
	},
	// 完善奖品收货信息
	toHandleInfo:function(){
		wx.navigateTo({
			url: '/pages/awardInfo/index',
		})
	},
	handleJoin: async function (e) {
		let {isMeetCondition,hasGetStatus} = this.data
		let activityId = e.currentTarget?.dataset?.id
		if (!app.isLogin()) {
			//登录页面跳转判断是点击了加入训练
			wx.setStorageSync('handleShare', 0)
			wx.setStorageSync('activityId', activityId)
			const url = `/pages/activity/practiceAward/index`
			app.navTo(url)
			return
		}
		// 是否绑定患者档案
		let patientInfo = wx.getStorageSync('patientInfo')
		if (!patientInfo) {
			app.globalData.createPatientEntrance = 9
			wx.setStorageSync('activityId', activityId)
			wx.navigateTo({
				url: '/pages/createPatient/select/select',
			})
			return
		}
		if(isMeetCondition===0){
			let userId = wx.getStorageSync('userId')
			const res = await request.post(api.joinTrain,{activityTrainingId:activityId,userId})
			console.log('加入活动场景',res);
			if(res.httpStatus===200){
				wx.showToast({
					title: res.msg,
					icon:'none'
				})
				if(res.msg==='成功加入训练'){
					this.setData({
						hasGetStatus: false
					})
					this.getTodayTaskList()
				}
			}else{
				wx.showToast({
					title: res.msg,
					icon:'none'
				})
			}
		}
	},
	// 获取活动状态
	getActivityStatus: async function (activityTrainingId) {
		let {GreenHeight} = this.data
		const res = await request.get(api.getUserActivityStatus, {
			// activityTrainingId
		}, {
			loading: false
		})

		this.init1(1) // 花朵动画

		console.log('活动状态', res);
		if (res.httpStatus === 200) {
			const {isFillAddress,isMeetCondition,trainingName} = res.data
			this.setData({
				isFillAddress,
				isMeetCondition,
				trainingName,
				hasGetStatus:true,
				GreenHeight:GreenHeight-124,
				break:trainingName!==''&&trainingName&&isMeetCondition!==1
			})
			if(isMeetCondition===1){
				this.getCompleteTrainList()
				this.init2()
			}else{
				this.getTrainListData()
			}
			// 没填写信息
			if(isFillAddress===0){
				this.init3()
			}
		}
	},
	// 获取当日训练任务列表-无任务没加入-有任务说明已经加入训练看完成未完成
	getTodayTaskList: async function () {
		const res = await request.get(api.getTodayTask, {}, {
			loading: false
		})
		console.log('今日列表', res);
		if (res.httpStatus === 200) {
			// 存在今日任务
			if (res.data.detailsList&&res.data.detailsList.length>0) {
				const {
					detailsList,
					isLastDayTask,
					trainingName,
					isAllComplete
				} = res.data
				this.setData({
					todayTaskList: [...detailsList],
					break:detailsList.length===0,
					trainingName,
					isLastDayTask,
					isAllComplete,
					showSceneList:[]
				})
				console.log('kkkkkk',this.data.todayTaskList.length);
				// 活动最后一天
				if(isLastDayTask===1&&isAllComplete===1){
					// 获取活动状态
					this.getActivityStatus(res.data.trainingId)
				}else{
					this.init1(2) // 五边形动画
				}
			}else{
				this.getActivityStatus(res.data.trainingId)
				this.init1(1) // 花朵动画     
			}
		}
	},
	// 获取训练列表
	getTrainListData: async function () {
		const res = await request.get(api.getTrainList, {}, {
			loading: false
		})
		console.log('训练列表', res);
		if (res.httpStatus === 200) {
			this.setData({
				showSceneList: res.data,
			})
		}
	},

	// 初始化加载训练场景左右循环动画
	init1(num) {
		if (this.inited1) {
			return
		}
		wx.createSelectorQuery()
			.selectAll('#practiceAward_lott1')
			.node((res) => {
				const canvas = res[0]?.node
				if (canvas) {
					const context = canvas.getContext('2d')
					canvas.width = 750 //datajs里边的宽高
					canvas.height = 1850

					lottie.setup(canvas)
					this.ani = lottie.loadAnimation({
						loop: true,
						autoplay: true,
						animationData: num===2?require('./data2.js'):require('./data.js'),
						rendererSettings: {
							context,
						},
					})
					this.inited1 = true
				}

			})
			.exec()
	},

	// 初始化加载挑战成功动画
	init2() {
		if (this.inited2) {
			return
		}
		wx.createSelectorQuery()
			.selectAll('#practiceAward_lott2')
			.node((res) => {
				const canvas = res[0]?.node
				if (canvas) {
					const context = canvas.getContext('2d')
					canvas.width = 750
					canvas.height = 200
					lottie.setup(canvas)
					this.ani = lottie.loadAnimation({
						// loop: true,
						autoplay: true,
						animationData: require('./chanllgeAM/data.js'),
						rendererSettings: {
							context,
						},
					})
					this.inited2 = true
				}
			})
			.exec()
	},
	// 初始化加载挑战成功-填写动画
	init3() {
		if (this.inited3) {
			return
		}
		wx.createSelectorQuery()
			.selectAll('#practiceAward_lott3')
			.node((res) => {
				const canvas = res[0]?.node
				if (canvas) {
					const context = canvas.getContext('2d')
					canvas.width = 750
					canvas.height = 200
					lottie.setup(canvas)
					this.ani = lottie.loadAnimation({
						loop: true,
						autoplay: true,
						animationData: require('./dataAdress.js'),
						rendererSettings: {
							context,
						},
					})
					this.inited3 = true
				}
			})
			.exec()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		this.shareSheet = this.selectComponent('#shareSheet')
		this.ruleSheet = this.selectComponent('#ruleSheet')
		this.infoSheet = this.selectComponent('#infoSheet')
	},
 	showInfo: async function() {
		const res = await request.get(api.getHonoreeInfo,{})
		console.log('ljxx',res);
		this.setData({
			LJInfo:{...res.data},
			showSheet: true
		})
		this.infoSheet.show()
	},
	showRule() {
		this.setData({
			showSheet: true
		})
		this.ruleSheet.show()
	},
	hideInfoSheet: function () {
		this.setData({
			showSheet: false
		})
		this.infoSheet.hide()
	},
	hideRuleSheet: function () {
		this.setData({
			showSheet: false
		})
		this.ruleSheet.hide()
	},
	handleShare: function () {
		let { activityId } = this.data
    const router = `/pages/activity/practiceAward/index?activityId=${activityId}`
    if (!app.isLogin()) {
			wx.setStorageSync('activityId', activityId)
			//登录页面跳转判断是点击了分享
			wx.setStorageSync('handleShare', 1)
      app.navTo(router)
    } else {
      this.setData({
        showPoster: true,
      })
      this.shareSheet.show()
    }
	},
	hideShareSheet: function () {
		this.setData({
			showPoster: false,
		})
		this.shareSheet.hide()
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		 // 获取活动详情判断活动状态
		 this.getActivityDetail()
		 
		// 登陆之后获取今日任务
		if (app.isLogin()) {
			let patientInfo = wx.getStorageSync('patientInfo')
			if(patientInfo){
				this.getTodayTaskList()
			}else{
				this.init1(1) // 花朵动画
			}
			if(!this.data.codeImg){
				this.getQRCode()
			}
		}else{
			this.init1(1) // 花朵动画
		}
		
	},
	savePhoto: function () {
		let that = this
		let {
			posterImg,
			codeImg
		} = that.data
		wx.downloadFile({
			url: posterImg,
			success(res) {
				console.log('downloadFile','sucess');
				const ctx = wx.createCanvasContext('myCanvas', that)
				wx.getImageInfo({
					src: posterImg,
					success: function (res) {
						// 绘制背景海报到canvas
						var sysInfo = wx.getSystemInfoSync()
						let windowWidth = sysInfo.windowWidth
						var scale = (windowWidth / 375) * 0.92 //不同屏幕下canvas的适配比例；设计稿是750宽
						let imgW = 274 * scale // 274
						let imgH = 407 * scale // 407
						let imgPath = res.path
						let codeSize = 80 * scale

						that.setData({
							canvasHeight: imgH,
							canvasWidth: imgW,
							canvasLeft: (windowWidth - imgW) / 2,
						})
						ctx.drawImage(imgPath, 0, 0, imgW, imgH)
						wx.getImageInfo({
							src: codeImg,
							success: function (res) {
								// 图片的x坐标
								let bg_x = (imgW - codeSize) / 2 // 10
								// 图片的y坐标
								let bg_y = imgH - codeSize - 35 // 70
								// 图片宽度
								let bg_w = codeSize
								// 图片高度
								let bg_h = codeSize
								// 图片圆角
								let bg_r = 6
								// 绘制海报背景图片圆角
								ctx.save()
								ctx.beginPath()
								ctx.arc(bg_x + bg_r, bg_y + bg_r, bg_r, Math.PI, Math.PI * 1.5)
								ctx.arc(bg_x + bg_w - bg_r,bg_y + bg_r,bg_r,Math.PI * 1.5,Math.PI * 2)
								ctx.arc(bg_x + bg_w - bg_r,bg_y + bg_h - bg_r,bg_r,0,Math.PI * 0.5)
								ctx.arc(bg_x + bg_r,bg_y + bg_h - bg_r,bg_r,Math.PI * 0.5,Math.PI)
								ctx.clip()
								ctx.drawImage(res.path, bg_x, bg_y, bg_w, bg_h)
								ctx.draw()
								setTimeout(() => {
									wx.canvasToTempFilePath({
											canvasId: 'myCanvas',
											success: function (res) {
												that.setData({
													imagePath: res.tempFilePath,
												})
											},
											fail: function (res) {},
										},
										this
									)
								}, 1000)
							},
						})
					},
				})
			},
		})
	},
	// 生成小程序码
	async getQRCode() {
		let {activityId} = this.data
		if(activityId){
			const res = await request.get(
				api.createQrcodeImg, {
					activityId: activityId,
				}, {
					loading: false
				}
			)
			if (res.httpStatus === 200) {
				this.setData({
					codeImg: res.data,
				})
				this.savePhoto()
			}
		}
	},
	// 保存海报
	handleSave() {
		wx.showLoading({
			title: '保存中...',
			mask: true
		})
		setTimeout(() => {
			wx.hideLoading()
			let {
				imagePath
			} = this.data
			saveImage(imagePath)
		}, 1500)
	},
	// 复制微信号
	handleCopy() {
		wx.setClipboardData({
			data: 'zhibaobao01',
			success: function (res) {
				wx.showToast({
					title: '复制成功',
					icon: 'success',
				})
			},
		})
	},
	// 获取活动详情
  async getActivityDetail() {
    let { activityId } = this.data
    const res = await request.get(
      api.activityDetail,
      {
        activityId: activityId,
      },
      { loading: false }
    )
    if (res.httpStatus === 200) {
			let info = res.data
			console.log('活动详情',info);
			const {startTime,endTime} = info
      this.setData({
				activityDetail:{...info,startTime:startTime.substring(0,10),endTime:endTime.substring(0,10)},
        activityActive: !app.isLogin()
          ? true
          : info.activityState === 2 && info.isPutaway === 1,
      })
    }
  },
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		wx.switchTab({
			url: '/pages/index/index',
		})
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let { activityId } = this.data
    const userId = wx.getStorageSync('userId')
    return {
      title: '可知成长邀您领实物好礼，包邮到家',
      path: `/pages/index/index?fromShare=practiceAward&activityId=${activityId}&userId=${userId}`,
      imageUrl:
        'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend7ac3684b69484eaebe33de50ddaebc04.png',
    }
  },
})